var gulp = require("gulp");
var browserify = require("browserify");
var plugins = require("gulp-load-plugins")();
var gulpsync = require("gulp-sync")(gulp);

var babelify = require("babelify");
var standalonify = require("standalonify");
var source = require("vinyl-source-stream");
var buffer = require("vinyl-buffer");
var fs = require("fs");
//
let baseURL = "/act/webcdkey/";
/**
 * 默认gulp任务
 * 命令：gulp
 */
gulp.task(
  "default",
  gulpsync.sync([
    "clear",
    "assets",
    "css",
    "tpl",
    "watch",
    "browserify",
    "web"
  ]),
  function () {
    console.log("编译完成");
  }
);
/**
 * 开启WEB服务
 */
gulp.task("web", function () {
  gulp.src("dist/").pipe(
    plugins.webserver({
      fallback: "index.html",
      livereload: true,
      open: false,
      port: 3000
    })
  );
});
/**
 * 清理编译项目目录
 */
gulp.task("clear", function () {
  return gulp.src(["dist"], {
    read: false
  }).pipe(plugins.clean());
});
/**
 * 监控文件修改 刷新网页
 */
gulp.task("watch", () => {
  gulp.watch("src/*.html", ["tpl", "browserify"]);
  //gulp.watch("src/tpl/*.tpl", ["tpl", "browserify"]);
  gulp.watch("src/css/*.css", ["css", "browserify"]);
  gulp.watch("src/js/*.js", ["browserify"]);
  gulp.watch("src/*.js", ["browserify"]);
});
/**
 * 编译项目将 ES6转换成ES5
 */
gulp.task("browserify", function () {
  var b = browserify({
    entries: "src/app.js",
    debug: true
  });
  return b
    .plugin(standalonify, {
      name: "FlareJ",
      deps: {
        nornj: "nj",
        react: "React",
        "react-dom": "ReactDOM"
      }
    })
    .transform(babelify, {
      presets: [
        ["env", {
          "targets": {
            "browsers": ["last 2 versions", "safari >= 7"]
          }
        }]
      ]
    })
    .bundle()
    .pipe(source("bundle.js"))
    .pipe(buffer())
    .pipe(
      plugins.uglify({
        mangle: false,
        compress: {
          properties: false
        },
        output: {
          quote_keys: true
        }
      })
    )
    .pipe(plugins.sourcemaps.init({
      loadMaps: true
    }))
    .pipe(plugins.sourcemaps.write("."))
    .pipe(gulp.dest("dist"));
});
/**
 * 资源图片压缩
 */
gulp.task("assets", function () {
  gulp
    .src("src/assets/*.*")
    .pipe(plugins.imagemin())
    .pipe(gulp.dest("dist/assets/"));
});
/**
 * 模版文件替换
 */
gulp.task("tpl", function () {
  var staticize = {
    getFileContent: function (tplPathName) {
      let filePath = tplPathName;
      var readFile = "";
      try {
        fs.accessSync(filePath);
        readFile = fs.readFileSync(filePath, "utf8");
        return readFile;
      } catch (err) {
        console.log(filePath + " is not exit ");
        return "";
      }
    }
  };

  var data = {
    //body: staticize.getFileContent("src/tpl/body.tpl"),
    js: {
      src: baseURL + "bundle.js",
      tpl: '<script src="%s"></script>'
    },
    jsbridge: {
      src: baseURL + "assets/jsbridge.js",
      tpl: '<script src="%s"></script>'
    },
    css: {
      src: baseURL + "css/style.min.css",
      tpl: '<link href="%s" rel="stylesheet">'
    }
  };
  var options = {
    removeComments: true,
    collapseWhitespace: true,
    minfyJS: true,
    minfyCss: true,
    removeAttributeQuotes: false
  };
  gulp
    .src("src/index.html")
    .pipe(plugins.htmlReplace(data))
    .pipe(plugins.htmlmin(options))
    .pipe(gulp.dest("dist"));
});
/**
 * CSS压缩
 */
gulp.task("css", () => {
  return gulp
    .src(["src/css/normalize.css", "src/css/common.css", "src/css/*.css"])
    .pipe(plugins.concat("css/style.css"))
    .pipe(plugins.cleanCss({
      compatibility: "ie8"
    }))
    .pipe(plugins.cssnano())
    .pipe(
      plugins.autoprefixer({
        browsers: ["last 2 versions", "Android >= 4.0"],
        cascade: false
      })
    )
    .pipe(
      plugins.rename(function (path) {
        path.basename += ".min";
      })
    )

    .pipe(gulp.dest("dist"));
});